package com.uenpay.im.ui.old.activity.choosemorepic;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.protocol.SysAccount;
import com.qyx.android.weight.choosemorepic.PhotoAibum;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.qyx.android.weight.utils.QyxWeightDensityUtils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.view.PictureShowActivity;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 相册
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class PhotoActivity extends BaseActivity implements
        PhotoAibumAdapter.OnItemClickListener2, PhotoAdappter.onItemSelectListener {

    public static final int CODE_REQUEST_VIEW_PHOTO = 101;

    private GridView gv;
    private PhotoAibum aibum = new PhotoAibum();
    private PhotoAdappter adapter;
    private TextView middleText;
    private int chooseNum = 0;
    private int selected_count;
    private Button btn_sure;
    private LayoutInflater inflater;
    private ArrayList<PhotoItem> gl_arr = new ArrayList<PhotoItem>();
    private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();
    private List<PhotoAibum> aibumList;
    private Dialog dialog;
    private TextView choose_dir;
    private PhotoAibumAdapter aibumAdapter;
    private int screenHeight;
    private int max_select_count;

    private PhotoItem mViewPhoto = null; //前往预览界面的photo

    private static final String[] STORE_IMAGES = {
            MediaStore.Images.Media.DISPLAY_NAME, // 名称
            MediaStore.Images.Media.DATA, MediaStore.Images.Media.LONGITUDE, // 日期
            MediaStore.Images.Media._ID, // id
            MediaStore.Images.Media.BUCKET_ID, // 目录id
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME, // 目录名称
            MediaStore.MediaColumns.DATE_MODIFIED, MediaStore.MediaColumns.SIZE

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_photoalbum_gridview;
    }

    @Override
    public void initView(View view) {
        aibumList = getPhotoAlbum();
        initView();
        initListener();
        initDialog();
    }

    protected void initView() {
        max_select_count = getIntent().getIntExtra("max_select_count", 1);
        screenHeight = QyxWeightDensityUtils.getScreenHeight(this);
        if (aibumList != null && aibumList.size() > 0) {
            aibum = aibumList.get(0);
        }
        selected_count = getIntent().getIntExtra("selected_count", 0);
        chooseNum = selected_count;
        int count = aibum.getBitList().size();
        for (int i = 0; i < count; i++) {
            if (aibum.getBitList().get(i).isSelect()) {
                chooseNum++;
            }
        }
        btn_sure = (Button) findViewById(R.id.btn_sure);
        middleText = (TextView) findViewById(R.id.title_textview);
        middleText.setText(R.string.photo);
        gv = (GridView) findViewById(R.id.photo_gridview);
        adapter = new PhotoAdappter(this, aibum, null);
        gv.setAdapter(adapter);
        adapter.setOnItemSelectListener(this);
        choose_dir = (TextView) findViewById(R.id.choose_dir);
        if (!TextUtils.isEmpty(aibum.getName())
                && !TextUtils.isEmpty(aibum.getCount())) {
            choose_dir.setText(aibum.getName() + " (" + aibum.getCount() + ")");
        }
    }

    /**
     */
    protected void initListener() {

        //返回键点击
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        gv.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case OnScrollListener.SCROLL_STATE_FLING:
                        if (adapter != null) {
                            adapter.SetIsScrolling(true);
                        }
                        break;
                    case OnScrollListener.SCROLL_STATE_IDLE:
                        if (adapter != null) {
                            adapter.SetIsScrolling(false);
                        }
                        int startindex = gv.getFirstVisiblePosition();
                        int endindex = gv.getLastVisiblePosition();
                        for (int currentpostion = startindex; currentpostion <= endindex; currentpostion++) {
                            View convertView = gv.getChildAt(currentpostion
                                    - startindex);
                            if (convertView != null
                                    && convertView instanceof PhotoGridItem) {
                                PhotoGridItem item = (PhotoGridItem) convertView;
                                if (item.mImageView.getVisibility() == View.VISIBLE) {
                                    item.mImageView.StopScroll();
                                }
                            }
                        }
                        break;
                    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        if (adapter != null) {
                            adapter.SetIsScrolling(false);
                        }
                        break;
                }

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

            }
        });

        btn_sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                data.putExtra("gl_arr", select_gl_arr);
                setResult(RESULT_OK, data);
                finish();
            }
        });

        choose_dir.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                } else {
                    dialog.show();
                }
            }
        });

    }

    private void inite(PhotoItem str, boolean isSeclect) {

        if (isSeclect) {
            btn_sure.setText(getResources().getString(R.string.complete) + "("
                    + select_gl_arr.size() + "/"
                    + (max_select_count - selected_count) + ")");
        } else {
            btn_sure.setText(getResources().getString(R.string.complete) + "("
                    + select_gl_arr.size() + "/"
                    + (max_select_count - selected_count) + ")");
        }
    }

    private void initDialog() {
        inflater = LayoutInflater.from(PhotoActivity.this);
        View view = inflater.inflate(R.layout.list_dir, null);
        ListView dir_list = (ListView) view.findViewById(R.id.id_list_dir);

        if (aibumAdapter == null) {
            aibumAdapter = new PhotoAibumAdapter(aibumList, this);
            aibumAdapter.setOnItemClickListener(this);
        } else {
            aibumAdapter.setData(aibumList);
        }
        dir_list.setAdapter(aibumAdapter);

        dialog = new Dialog(this, R.style.pop_dialog);
        dialog.setContentView(view);
        Window win = dialog.getWindow();
        win.setGravity(Gravity.BOTTOM);
        win.setWindowAnimations(R.style.dialogWindowAnim);
        dialog.setCanceledOnTouchOutside(true);
        // dialog.show();
        win.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                screenHeight / 2);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.y = Utils.dip2px(this, 48);
        win.setAttributes(lp);
    }

    @SuppressLint("DefaultLocale")
    private List<PhotoAibum> getPhotoAlbum() {
        PhotoAibum all = new PhotoAibum();
        List<PhotoAibum> aibumList = new ArrayList<PhotoAibum>();
        Cursor cursor = MediaStore.Images.Media.query(getContentResolver(),
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, "",
                MediaStore.MediaColumns.DATE_ADDED + " DESC");
        Map<String, PhotoAibum> countMap = new HashMap<String, PhotoAibum>();
        PhotoAibum pa = null;
        int i = 0;
        String first_id = "";
        if (cursor == null) {
            return aibumList;
        }
        while (cursor.moveToNext()) {
            long size = cursor.getLong(7);
            if (size <= 0) {
                continue;
            }
            String path = cursor.getString(1);
            String id = cursor.getString(3);
            String dir_id = cursor.getString(4);
            String dir = cursor.getString(5);
            long datemodified = cursor.getLong(6);

            if (i == 0) {
                first_id = id;
            }
            // Log.e("info", "id===" + id + "==dir_id==" + dir_id + "==dir=="
            // + dir + "==path=" + path);
            PhotoItem photoItem = new PhotoItem(Integer.valueOf(id), path,
                    datemodified);
            all.addBit(photoItem);
            if (!countMap.containsKey(dir_id)) {
                pa = new PhotoAibum();
                pa.setName(dir);
                pa.setBitmap(Integer.parseInt(id));
                pa.setCount("1");
                pa.getBitList().add(photoItem);
                countMap.put(dir_id, pa);
            } else {
                pa = countMap.get(dir_id);
                pa.setCount(String.valueOf(Integer.parseInt(pa.getCount()) + 1));
                pa.getBitList().add(photoItem);
            }

            i++;
        }
        cursor.close();
        Iterable<String> it = countMap.keySet();

        for (String key : it) {
            aibumList.add(countMap.get(key));
        }

        all.setName(getResources().getString(R.string.all_photo));
        all.setCount(all.getBitList().size() + "");
        if (!first_id.equals("")) {
            all.setBitmap(Integer.parseInt(first_id));
        }
        aibumList.add(0, all);
        return aibumList;
    }

    @Override
    public void onItemClickListener(PhotoAibum aibum) {
        dialog.dismiss();
        this.aibum = aibum;
        choose_dir.setText(aibum.getName() + " (" + aibum.getCount() + ")");
        if (adapter != null) {
            adapter.RecycleMaskImageView(true);
        }
        adapter.setData(aibum);
        gv.postDelayed(new Runnable() {
            @Override
            public void run() {
                gv.setSelection(0);
            }
        }, 200);
    }

    @Override
    public void onItemSelect(int pos, PhotoItem gridItem,
                             PhotoGridItem photoGridItem) {
        if (gridItem.isSelect()) {
            gridItem.setSelect(false);
            gl_arr.remove(gridItem);
            chooseNum--;
            select_gl_arr.remove(gridItem);
            inite(gridItem, gridItem.isSelect());
            if (photoGridItem != null) {
                photoGridItem.setChecked(false);
            }
        } else {
            if (chooseNum == max_select_count) {

                IMApplication.showToast(MessageFormat.format(getResources()
                        .getString(R.string.most_num), max_select_count));
                return;
            }
            gridItem.setSelect(true);
            gl_arr.add(gridItem);
            select_gl_arr.add(gridItem);
            chooseNum++;
            inite(gridItem, gridItem.isSelect());
            if (photoGridItem != null) {
                photoGridItem.setChecked(true);
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.RecycleMaskImageView(true);
        }
        IMApplication.getInstance().removeActivity(this);
        super.onDestroy();
    }

    @Override
    public void onImgClick(PhotoItem photoItem) {
        String bigpath = "";
        if (!TextUtils.isEmpty(photoItem.getPath())) {
            bigpath = photoItem.getPath();
        } else {
            return;
        }
        mViewPhoto = photoItem;
        ArrayList<String> imgs = new ArrayList<String>();

        Intent show = new Intent(PhotoActivity.this, PictureShowActivity.class);
        show.putExtra("cust_id", SysAccount.TEAM + "");
        show.putExtra("cust_name", getResources().getString(R.string.app_name));
        show.putExtra("content", bigpath);
        show.putExtra("is_from_photo_activity", true);
        imgs.add(bigpath);
        show.putStringArrayListExtra("imgList", imgs);
        startActivityForResult(show, CODE_REQUEST_VIEW_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_VIEW_PHOTO && resultCode == RESULT_OK) {
            if (mViewPhoto != null) {
                Intent photoData = new Intent();
                ArrayList<PhotoItem> list = new ArrayList<>();
                list.add(mViewPhoto);
                photoData.putExtra("gl_arr", list);
                setResult(RESULT_OK, photoData);
                finish();
            }
        }
    }
}
